package listener

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "strconv"
    
    "collecter/app/cache"
    "collecter/app/common/enum"
    "collecter/app/common/helper"
    "collecter/app/common/service"
    "collecter/app/event/interfaces"
    "collecter/app/model"
)

type UserRegister struct {
    EventName   string
    SubjectId   int64
    ExtraParams string
}

func (ur UserRegister) SetValue(eventName string, subjectId int64, extraParams string) interfaces.EventInterfacer {
    ur.EventName = eventName
    ur.SubjectId = subjectId
    ur.ExtraParams = extraParams
    return ur
}

func (ur UserRegister) Handle() error {
    fmt.Println("UserRegister event is listen ... ")
    fmt.Printf(" UserRegister-->Handle: %+v\n", ur)
    
    var user model.Users
    user.Id = ur.SubjectId
    if err := helper.Db.Where(&user).First(&user).Error; err != nil {
        errmsg := "用户注册事件监听失败：查询用户数据失败。errmsg：" + err.Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    
    // 创建用户默认分类
    category := service.NewCategory(user.Id)
    category.CateName = "默认"
    category.Sort = 1
    if err := category.Create(); err != nil {
        errmsg := "用户注册事件监听失败：创建用户默认分类失败。errmsg：" + err.Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    
    activateCode := helper.GenerateRandomString(16)
    pms := make(map[string]string)
    pms["account"] = user.Account
    pms["register_time"] = strconv.FormatInt(user.LastModifyPasswordTime, 10)
    pms["activate_code"] = activateCode
    var pmByte []byte
    if val, err := json.Marshal(pms); err != nil {
        errmsg := "用户注册事件监听失败：json 编码请求参数失败。errmsg：" + err.Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    } else {
        pmByte = val
    }
    pmStr := base64.StdEncoding.EncodeToString(pmByte)
    domain := helper.Configer.GetString("domain")
    activateUrl := domain + "/api/authorize/activate?pm=" + pmStr
    vcode := service.NewVcode("", "accountActivate")
    if helper.RegExpVerify(user.Email, "email") {
        vcode.Account = user.Email
    } else if helper.RegExpVerify(user.Mobile, "mobile") {
        vcode.Account = user.Mobile
    } else {
        errmsg := "用户注册事件监听失败：用户未使用手机号和邮箱账号"
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    if err := vcode.SendVcode(activateUrl); err != nil {
        errmsg := "用户注册事件监听失败：发送激活信息（邮件或者短信）失败。errmsg：" + err.Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    cacheKey := enum.USER_ACTIVATE_CODE + user.Account
    if err := cache.Cacher.Set(cacheKey, activateCode, 0); err != nil {
        errmsg := "用户注册事件监听失败：缓存激活码失败。errmsg：" + err.Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    return nil
}
